//
// Created by 下次一定 on 2021/9/16.
//
/*
 * 遍历图
 * */

#include <iostream>
#include <algorithm>
#include<queue>

using namespace std;

typedef pair<int, int> PII;
const int N = 1010;
int map[N][N];
int d[N][N];
int n, m;
PII q[N * N];

int bfs() {
    q[0] = {0,0};
    queue<PII> queue;
    queue.push(q[0]);
    d[0][0] = 0;
    map[0][0] = 2;
    int dx[4] = {-1,0,0,1},dy[4] = {0,-1,1,0};

    while(!queue.empty()){
        PII t = queue.front();
        queue.pop();

        int x = t.first;
        int y = t.second;
        for(int i = 0 ; i < 4; i ++){
            int nx = x + dx[i];
            int ny = y + dy[i];
            if(nx>=0 && nx < n && ny >= 0 && ny < m && map[nx][ny] ==0){
                t = {nx,ny};
                queue.push(t);
                d[nx][ny] = d[x][y] + 1;
                map[x][y] = 2;
            }
        }

    }

    return d[n-1][m-1];

}

int main() {
    cin >> n >> m;

    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            cin >> map[i][j];
    cout << bfs();

}